<template>
  <div class="app-container">
    <!-- 搜索查询 -->
    <div class="filter-container">
      <el-row :gutter="24">
        <el-col :sm="12" :md="8" :lg="4">
          <el-input v-model="listQuery.title" placeholder="标题" class="filter-item" />
        </el-col>
        <el-col :sm="18" :md="12" :lg="6">
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >查询</el-button>
          <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="addList">新增</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" label="Date">
        <template slot-scope="scope">
          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column width="120px" align="center" label="Author">
        <template slot-scope="scope">
          <span>{{ scope.row.author }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100px" label="Importance">
        <template slot-scope="scope">
          <svg-icon
            v-for="n in +scope.row.importance"
            :key="n"
            icon-class="star"
            class="meta-item__icon"
          />
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="Status" width="110">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">{{ row.status }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column min-width="300px" label="Title">
        <template slot-scope="{row}">
          <router-link :to="'/example/edit/'+row.id" class="link-type">
            <span>{{ row.title }}</span>
          </router-link>
        </template>
      </el-table-column>

      <el-table-column align="center" label="Actions" width="200">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            @click="handelEditShow(scope)"
          >Edit</el-button>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            @click="deleteList(scope)"
          >Delete</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页插件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 新增和修改弹框 -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'修改':'新增'">
      <el-form
        ref="form"
        :model="form"
        :rules="formRules"
        class="login-form"
        autocomplete="on"
        label-position="left"
      >
        <el-form-item label="标题" prop="title" label-width="100px">
          <el-input v-model="form.title" placeholder="请输入用户名" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button
          type="danger"
          @click="change_seetting({key: 'showSettings',
                                   value: !showSettings})"
        >关闭</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  updateArticle,
  deleteArticle,
  createArticle
} from '@/api/article' // 引入api接口
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { mapMutations, mapActions, mapGetters, mapState } from 'vuex'

export default {
  name: 'ArticleList',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('输入框不能为空'))
      } else {
        callback()
      }
    }
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        title: ''
      },
      dialogType: 'new',
      dialogVisible: false,
      form: {
        title: ''
      },
      formRules: {
        title: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ]
      }
    }
  },
  computed: {
    // ...mapGetters(['showSettings'])
    ...mapState({
      showSettings: state => state.settings.showSettings
    })
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表（查）
    // 将vuex里actions里面的方法映射到当前组件
    ...mapActions({
      change_seetting: 'settings/changeSetting'
    }),
    // 将vuex里mutations里面的方法映射到当前组件
    // ...mapMutations({
    //   change_seetting: 'settings/CHANGE_SETTING'
    // }),
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.listQuery.limit = 10
      this.getList()
    },
    // 打开修改弹框
    handelEditShow(data) {
      this.$store.dispatch('settings/changeSetting', { key: 'showSettings',
        value: !this.showSettings })
      // this.$store.commit('settings/CHANGE_SETTING', {key: 'showSettings',
      //     value: !this.showSettings})
      this.form = {
        id: data.row.id,
        title: data.row.title
      }
      this.dialogType = 'edit'
      this.dialogVisible = true
    },
    // 新增
    addList() {
      this.form = {
        title: ''
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    // 删除
    deleteList(data) {
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteArticle({ id: data.row.id }).then(data => {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 新增和修改提交
    confirmRole() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.dialogType === 'new') {
            delete this.form.id // 新增删除id属性
            createArticle(this.form).then(data => {
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.dialogVisible = false
              this.getList()
            })
          } else {
            updateArticle(this.form).then(data => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
